package com.xzc.lease.web.admin.service.impl;

import com.xzc.lease.model.entity.*;
import com.xzc.lease.web.admin.mapper.*;
import com.xzc.lease.web.admin.service.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xzc.lease.common.exception.LeaseException;
import com.xzc.lease.common.result.ResultCodeEnum;
import com.xzc.lease.model.entity.*;
import com.xzc.lease.model.enums.ItemType;
import com.xzc.lease.web.admin.mapper.*;
import com.xzc.lease.web.admin.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xzc.lease.web.admin.vo.apartment.ApartmentDetailVo;
import com.xzc.lease.web.admin.vo.apartment.ApartmentItemVo;
import com.xzc.lease.web.admin.vo.apartment.ApartmentQueryVo;
import com.xzc.lease.web.admin.vo.apartment.ApartmentSubmitVo;
import com.xzc.lease.web.admin.vo.fee.FeeValueVo;
import com.xzc.lease.web.admin.vo.graph.GraphVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 徐生
 * @description 针对表【apartment_info(公寓信息表)】的数据库操作Service实现
 * @createDate 2023-07-24 15:48:00
 */
@Service
public class ApartmentInfoServiceImpl extends ServiceImpl<ApartmentInfoMapper, ApartmentInfo>
        implements ApartmentInfoService {

    @Autowired
    private GraphInfoService graphInfoService;
    @Autowired
    private ApartmentFacilityService apartmentFacilityService;
    @Autowired
    private ApartmentLabelService apartmentLabelService;
    @Autowired
    private ApartmentFeeValueService apartmentFeeValueService;
    @Autowired
    private ProvinceInfoMapper provinceInfoMapper;
    @Autowired
    private CityInfoMapper cityInfoMapper;
    @Autowired
    private DistrictInfoMapper districtInfoMapper;


    /**
     * 保存或更新公寓信息
     *
     * @param apartmentSubmitVo
     */
    public void saveOrUpdateApartment(ApartmentSubmitVo apartmentSubmitVo) {
        boolean isUpdate = apartmentSubmitVo.getId() != null;

        //在更新之前，修改保存或更新公寓信息不能显示公寓省市县的bug。
        //  原因是前端是更具 xxxname 来展示地址的，所以在新增时，虽然传入了地址id，但没有具体的name。 自己重新set 省市县name即可
        updateRegionName(apartmentSubmitVo);

        //该super指向的是 ServiceImpl
        //apartmentSubmitVo继承了ApartmentInfo，因此只会更新其父类的属性，自身的属性需要自己修改
        //该语句必须在 isUpdate属性之前，saveOrUpdate()执行后会把id给回显到apartmentSubmitVo中
        super.saveOrUpdate(apartmentSubmitVo);

        if (isUpdate) {
            //删除公寓关联的 图片、标签、配套、杂费信息
            deleteBatch(apartmentSubmitVo.getId());
        }

        //1、插入图片列表
        List<GraphVo> graphVoList = apartmentSubmitVo.getGraphVoList();
        if (!CollectionUtils.isEmpty(graphVoList)) {
            ArrayList<GraphInfo> graphInfosList = new ArrayList<>();
            //循环添加
            for (GraphVo graphVo : graphVoList) {
                //创建对象并给其 设置属性
                GraphInfo graphInfo = new GraphInfo();
                graphInfo.setName(graphVo.getName());
                graphInfo.setUrl(graphVo.getUrl());
                graphInfo.setItemType(ItemType.APARTMENT);
                graphInfo.setItemId(apartmentSubmitVo.getId());
                graphInfosList.add(graphInfo);
            }
            graphInfoService.saveBatch(graphInfosList);
        }

        //2、插入配套列表
        List<Long> facilityInfoIdList = apartmentSubmitVo.getFacilityInfoIds();
        //集合非空判断
        if (!CollectionUtils.isEmpty(facilityInfoIdList)) {
            //创建集合
            ArrayList<ApartmentFacility> facilityList = new ArrayList<>();
            //循环添加
            for (Long facilityId : facilityInfoIdList) {
                ApartmentFacility apartmentFacility = ApartmentFacility.builder()
                        .apartmentId(apartmentSubmitVo.getId())
                        .facilityId(facilityId)
                        .build();
                facilityList.add(apartmentFacility);
            }
            apartmentFacilityService.saveBatch(facilityList);
        }

        //3、插入标签列表
        List<Long> labelIdList = apartmentSubmitVo.getLabelIds();
        //集合非空判断
        if (!CollectionUtils.isEmpty(labelIdList)) {
            ArrayList<ApartmentLabel> apartmentLabelList = new ArrayList<>();
            for (Long labelId : labelIdList) {
                ApartmentLabel apartmentLabel = ApartmentLabel.builder()
                        .apartmentId(apartmentSubmitVo.getId())
                        .labelId(labelId)
                        .build();
                apartmentLabelList.add(apartmentLabel);
            }
            apartmentLabelService.saveBatch(apartmentLabelList);
        }

        //4、插入杂费列表
        List<Long> feeValueIdList = apartmentSubmitVo.getFeeValueIds();
        if (!CollectionUtils.isEmpty(feeValueIdList)) {
            ArrayList<ApartmentFeeValue> apartmentFeeValueList = new ArrayList<>();
            for (Long feeValueId : feeValueIdList) {
                ApartmentFeeValue apartmentFeeValue = ApartmentFeeValue.builder()
                        .apartmentId(apartmentSubmitVo.getId())
                        .feeValueId(feeValueId)
                        .build();
                apartmentFeeValueList.add(apartmentFeeValue);
            }
            apartmentFeeValueService.saveBatch(apartmentFeeValueList);
        }
    }


    @Autowired
    private ApartmentInfoMapper apartmentInfoMapper;

    /**
     * 根据条件分页查询公寓列表
     *
     * @param page
     * @param queryVo
     * @return
     */
    public IPage<ApartmentItemVo> pageItem(Page<ApartmentItemVo> page, ApartmentQueryVo queryVo) {
        return apartmentInfoMapper.pageItem(page, queryVo);
    }


    @Autowired
    private GraphInfoMapper graphInfoMapper;
    @Autowired
    private LabelInfoMapper labelInfoMapper;
    @Autowired
    private FacilityInfoMapper facilityInfoMapper;
    @Autowired
    private FeeValueMapper feeValueMapper;

    /**
     * 根据ID获取公寓详细信息
     *
     * @param id
     * @return
     */
    public ApartmentDetailVo getDetailById(Long id) {
        //1、查询公寓信息
        ApartmentInfo apartmentInfo = apartmentInfoMapper.selectById(id);

        //2、查询图片列表
        List<GraphVo> graphVoList = graphInfoMapper.selectListByItemTypeAndId(ItemType.APARTMENT, id);

        //3、查询标签列表
        List<LabelInfo> labelInfoList = labelInfoMapper.selectListByApartmentId(id);

        //4、查询配套列表
        List<FacilityInfo> facilityInfoList = facilityInfoMapper.selectListByApartmentId(id);

        //5、查询杂费列表
        List<FeeValueVo> feeValueVoList = feeValueMapper.selectListByApartmentId(id);

        //6、组装结果
        ApartmentDetailVo apartmentDetailVo = new ApartmentDetailVo();
        //将 第一个参数的值 赋值给第二个参数上
        BeanUtils.copyProperties(apartmentInfo, apartmentDetailVo);

        apartmentDetailVo.setGraphVoList(graphVoList);
        apartmentDetailVo.setLabelInfoList(labelInfoList);
        apartmentDetailVo.setFacilityInfoList(facilityInfoList);
        apartmentDetailVo.setFeeValueVoList(feeValueVoList);
        return apartmentDetailVo;
    }


    @Autowired
    private RoomInfoMapper roomInfoMapper;

    /**
     * 根据id删除公寓信息
     *
     * @param id
     */
    public void removeByApartmentId(Long id) {
        //查询公寓下 房间的个数
        LambdaQueryWrapper<RoomInfo> roomQueryWrapper = new LambdaQueryWrapper<>();
        roomQueryWrapper.eq(RoomInfo::getApartmentId, id);
        Long count = roomInfoMapper.selectCount(roomQueryWrapper);

        if (count > 0) { //公寓下 还有房间
            //终止删除，并且响应提示信息
            throw new LeaseException(ResultCodeEnum.ADMIN_APARTMENT_DELETE_ERROR);
        }

        //删除apartmentInfo数据（删除公寓数据）
        super.removeById(id);
        //删除公寓关联的 图片、标签、配套、杂费信息
        deleteBatch(id);
    }


    /**
     * 针对删除公寓时，一起删除相关图片、配套、列表、杂费的操作
     *
     * @param id
     */
    public void deleteBatch(Long id) {
        //1、删除图片列表
        LambdaQueryWrapper<GraphInfo> graphQueryWrapper = new LambdaQueryWrapper<>();
        graphQueryWrapper.eq(GraphInfo::getItemType, ItemType.APARTMENT);
        graphQueryWrapper.eq(GraphInfo::getId, id);
        graphInfoService.remove(graphQueryWrapper);

        //2、删除配套列表
        LambdaQueryWrapper<ApartmentFacility> facilityQueryWrapper = new LambdaQueryWrapper<>();
        facilityQueryWrapper.eq(ApartmentFacility::getApartmentId, id);
        apartmentFacilityService.remove(facilityQueryWrapper);

        //3、删除标签列表
        LambdaQueryWrapper<ApartmentLabel> labelQueryWrapper = new LambdaQueryWrapper<>();
        labelQueryWrapper.eq(ApartmentLabel::getApartmentId, id);
        apartmentLabelService.remove(labelQueryWrapper);

        //4、删除杂费列表
        LambdaQueryWrapper<ApartmentFeeValue> feeQueryWrapper = new LambdaQueryWrapper<>();
        feeQueryWrapper.eq(ApartmentFeeValue::getApartmentId, id);
        apartmentFeeValueService.remove(feeQueryWrapper);
    }

    /**
     * 设置省市区的name
     *
     * @param apartmentSubmitVo
     */
    public void updateRegionName(ApartmentSubmitVo apartmentSubmitVo) {
        //根据省份id查询省份name
        LambdaQueryWrapper<ProvinceInfo> provinceQueryWrapper = new LambdaQueryWrapper<>();
        provinceQueryWrapper.eq(ProvinceInfo::getId, apartmentSubmitVo.getProvinceId());
        ProvinceInfo provinceInfo = provinceInfoMapper.selectOne(provinceQueryWrapper);
        //根据市id查询省份name
        LambdaQueryWrapper<CityInfo> cityQueryWrapper = new LambdaQueryWrapper<>();
        cityQueryWrapper.eq(CityInfo::getId, apartmentSubmitVo.getCityId());
        CityInfo cityInfo = cityInfoMapper.selectOne(cityQueryWrapper);
        //根据县份id查询省份name
        LambdaQueryWrapper<DistrictInfo> districtQueryWrapper = new LambdaQueryWrapper<>();
        districtQueryWrapper.eq(DistrictInfo::getId, apartmentSubmitVo.getDistrictId());
        DistrictInfo districtInfo = districtInfoMapper.selectOne(districtQueryWrapper);
        //设置省市县的name
        apartmentSubmitVo.setProvinceName(provinceInfo.getName());
        apartmentSubmitVo.setCityName(cityInfo.getName());
        apartmentSubmitVo.setDistrictName(districtInfo.getName());
    }
}




